<?php
/**
 * 获取token
 */
function checkToken($uid,$appid,$secret){
	$acc_token = S ('access_token');
	if(!empty($acc_token)){
		return $acc_token;
	}else{
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&secret='.$secret.'&appid='.$appid;
		$tempArr = json_decode ( file_get_contents ( $url ), true );
		S ( 'access_token', $tempArr ['access_token'], $tempArr ['expires_in'] );
		return $tempArr['access_token'];
	}
}
/**
 * 获取用户信息
 */
function getweixininfo($token,$oppenid){
	$param2 ['access_token'] =$token;
	$param2 ['openid'] = $oppenid;
	$param2 ['lang'] = 'zh_CN';
	$url = 'https://api.weixin.qq.com/cgi-bin/user/info?' . http_build_query ( $param2 );
	$content = file_get_contents ( $url );
	$content = json_decode ( $content, true );
	/* if(empty($content['nickname'])){
		$appid = session('appid');
	$secret= session('secret');
	getweixin($secret,$appid);
	getweixininfo();
	} */
	return $content;
}
function sendemail($title,$content,$email){
	$basc = F('web_web');
	//$a = R('Public/new_email_send',array($title,$body));
	$host1=$basc['smtp'];
	$username=$basc['email_account'];
	$pass=$basc['email_password'];
	Vendor('PHPMailer.PHPMailerAutoload');
	$mail = new PHPMailer(); //实例化
	$mail->IsSMTP();                                       // set mailer to use SMTP
	$mail->Host = "$host1";     // specify main and backup server
	$mail->SMTPAuth = true;            // turn on SMTP authentication开启身份验证
	$mail->Username = "$username";        // SMTP username服务器用户名
	$mail->Password = "$pass";        // SMTP password服务器用户密码
	$mail->From = "$username";      //发件人E-mail
	$mail->FromName = $basc['email_name'];      //发件人名称
	$mail->AddAddress("$email",""); //收件人E-mail和称呼
	$mail->WordWrap = 50;                                  // set word wrap to 50 characters
	$mail->IsHTML(true);                                   // set email format to HTML
	$mail->Subject = "$title";    //邮件标题
	$mail->Body    = "$content";
	$mail->CharSet='utf-8';
	if(!$mail->Send())           //发送邮件
	{
		$result=0;
	}else{
		$result=1;
			
	}
	return  $result;
}
function http_request($url,$data=null){
	$curl = curl_init();
	curl_setopt($curl,CURLOPT_URL,$url );
	curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE );
	curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE );
	if( !empty($data) ){
		curl_setopt($curl,CURLOPT_POST,1 );
		curl_setopt($curl,CURLOPT_POSTFIELDS,$data );
	}
	curl_setopt($curl,CURLOPT_RETURNTRANSFER,1 );
	$result = curl_exec($curl);
	curl_close($curl);
	return $result;
}
//给图片路径添加url
function replacePicUrl($content = null, $strUrl = null) {
	if ($strUrl) {
		//提取图片路径的src的正则表达式 并把结果存入$matches中
		preg_match_all("/<img(.*)src=\"([^\"]+)\"[^>]+>/isU",$content,$matches);
		$img = "";
		if(!empty($matches)) {
			//注意，上面的正则表达式说明src的值是放在数组的第三个中
			$img = $matches[2];
		}else {
			$img = "";
		}
		if (!empty($img)) {
			$patterns= array();
			$replacements = array();
			foreach($img as $imgItem){
				if(stripos($imgItem,$strUrl)!==false){
					$final_imgUrl = $imgItem;
				}else{
					if(is_url($imgItem)){
						$final_imgUrl = $imgItem;
					}else{
						$final_imgUrl = $strUrl.$imgItem;
					}
					
				}
				$replacements[] = $final_imgUrl;
				$img_new = "/".preg_replace("/\//i","\/",$imgItem)."/";
				$patterns[] = $img_new;
			}

			//让数组按照key来排序
			ksort($patterns);
			ksort($replacements);

			//替换内容
			$vote_content = preg_replace($patterns, $replacements, $content);

			return $vote_content;
		}else {
			return $content;
		}
	} else {
		return $content;
	}
}
/**
 * 是否为一个合法的url
 * @param string $url
 * @return boolean
 */
function is_url($url){
	if (filter_var ($url, FILTER_VALIDATE_URL )) {
		return true;
	} else {
		return false;
	}
}

/**
 * 是否是手机号码
*
* @param string $phone 手机号码
* @return boolean
*/
function is_phone($phone) {
	if (strlen ( $phone ) != 11 || ! preg_match ( '/^1[3|4|5|8][0-9]\d{4,8}$/', $phone )) {
		return false;
	} else {
		return true;
	}
}
/**
 * 验证字符串是否为数字,字母,中文和下划线构成
 * @param string $username
 * @return bool
 */
function is_check_string($str){
	if(preg_match('/^[\x{4e00}-\x{9fa5}\w_]+$/u',$str)){
		return true;
	}else{
		return false;
	}
}
/**
 * 是否为一个合法的email
 * @param sting $email
 * @return boolean
 */
function is_email($email){
	if (filter_var ($email, FILTER_VALIDATE_EMAIL )) {
		return true;
	} else {
		return false;
	}
}
/**
 * 是否为一个合法的ip地址
 * @param string $ip
 * @return boolean
 */
function is_ip($ip){
	if (ip2long($ip)) {
		return true;
	} else {
		return false;
	}
}
/**
 * 是否为整数
 * @param int $number
 * @return boolean
 */
function is_number($number){
	if(preg_match('/^[-\+]?\d+$/',$number)){
		return true;
	}else{
		return false;
	}
}
/**
 * 是否为正整数
 * @param int $number
 * @return boolean
 */
function is_positive_number($number){
	if(ctype_digit ($number)){
		return true;
	}else{
		return false;
	}
}
/**
 * 是否为小数
 * @param float $number
 * @return boolean
 */
function is_decimal($number){
	if(preg_match('/^[-\+]?\d+(\.\d+)?$/',$number)){
		return true;
	}else{
		return false;
	}
}
/**
 * 是否为正小数
 * @param float $number
 * @return boolean
 */
function is_positive_decimal($number){
	if(preg_match('/^\d+(\.\d+)?$/',$number)){
		return true;
	}else{
		return false;
	}
}
/**
 * 是否为英文
 * @param string $str
 * @return boolean
 */
function is_english($str){
	if(ctype_alpha($str))
		return true;
	else
		return false;
}
/**
 * 是否为中文
 * @param string $str
 * @return boolean
 */
function is_chinese($str){
	if(preg_match('/^[\x{4e00}-\x{9fa5}]+$/u',$str))
		return true;
	else
		return false;
}
/**
 * 判断是否为图片
 * @param string $file  图片文件路径
 * @return boolean
 */
function is_image($file){
	if(file_exists($file)&&getimagesize($file===false)){
		return false;
	}else{
		return true;
	}
}
/**
 * 是否为合法的身份证(支持15位和18位)
 * @param string $card
 * @return boolean
 */
function is_card($card){
	if(preg_match('/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/',$card)||preg_match('/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/',$card))
		return true;
	else
		return false;
}
/**
 * 验证日期格式是否正确
 * @param string $date
 * @param string $format
 * @return boolean
 */
function is_date($date,$format='Y-m-d'){
	$t=date_parse_from_format($format,$date);
	if(empty($t['errors'])){
		return true;
	}else{
		return false;
	}
}

/**
 * 获取数据
 * @param unknown $map 查询条件
 * @param unknown $field 查询字段
 * @param string $order 排序字段
 * @param number $firstrow
 * @param unknown $listrow
 * @param unknown $type 1 单条查询 2是多条查询
 */
function lists($model,$join=null,$map=1,$field,$order="id desc",$firstrow=0,$listrow,$type){
	if($type == 1){
		if(!empty($join)){
			return M($model)->join($join)->field ( $field )->where ( $map )->order ( $order )->find();
		}else{
			return M($model)->field ( $field )->where ( $map )->order ( $order )->find();
		}
		
	}else{
		if(!empty($join)){
			if($listrow){
				return M($model)->join($join)->field ( $field )->where ( $map )->order ( $order )->limit($firstrow,$listrow)->select ();
			}else{
				return M($model)->join($join)->field ( $field )->where ( $map )->order ( $order )->select ();
			}
		}else{
			if($listrow){
				return M($model)->field ($field)->where ( $map )->order ( $order )->limit($firstrow,$listrow)->select ();
			}else{
				return M($model)->field ($field)->where ( $map )->order ( $order )->select ();
			}
		}
	}
}
/**
 * 图片展示
 */
function showimg($placeid){
	$re = M('ad_place')->where("id='{$placeid}' and status='0'")->find();
	if(!empty($re)){
		$today = date("Y-m-d");
		$list = M('ad')->where("place_id='{$placeid}' and status='0' and start_time <='{$today}' and end_time>='{$today}'")->field("photo,url")->select();
		$img = "";
		foreach ($list as $i=>$va){
			if(empty($va['url'])){
				$list[$i]['url'] = "javascript:void(0)" ;
			}
			//$img .= '<a href="'.$url[$i].'"><img src="'.$va['photo'].'"/></a>';
		}
		return $list;
	}else{
		return "此广告位置不存在";
	}
}
/**
 * 获取默认库存
 */
function defalut_store(){
	$basc = F('web_web');
	return $basc['default_store']?$basc['default_store']:'99';
}
/**
 * 获取商品、产品的货号
 */
function goods_no($k=0){
	$basc = F('web_web');
	$shop_number = $basc['shop_number']?$basc['shop_number']:'No';
	$goods_no = $shop_number.time().rand(11,99);
	if($k){
		$goods_no .= "-".$k;
	}
	return $goods_no;
}
/**
 * 获取商品的价格
 */
function goods_price($goods_id,$fields=null){
	$field = $fields?$fields:'sell_price';
	$db = M('products');
	$count= $db->where("goods_id='{$goods_id}'")->count();
	if($count == 1){
		$money = $db->where("goods_id='{$goods_id}'")->getField($field);
	}elseif($count == 0){
		$money = 0;
	}else{
		$max_money = $db->where("goods_id='{$goods_id}'")->max($field);
		$min_money = $db->where("goods_id='{$goods_id}'")->min($field);
		$money = $min_money."~".$max_money;
	}
	return $money;
}
/**
 * 获取商品分类
 */ 
function goods_class($goods_id,$separator=null){
    $categoryDb = M('category_extend as ce');
    $clas =  $categoryDb->join("".C('DB_PREFIX')."category as c on c.id = ce.category_id")->where("ce.goods_id='{$goods_id}'")->field("c.name")->select();
    foreach ($clas as $va){
    	$class_name[] = $va['name'];
    }
    if(!empty($separator)){
    	return join($separator,$class_name);
    }else{
    	return $class_name;
    }
   
}
/**
 * 获取产品数据 //根据规格来查
 */
function product_info($goods_id,$spec_id_string){
	$list = M('products')->where("goods_id='{$goods_id}' and spec_array='{$spec_id_string}'")->find();
	return $list;
}
/**
 * 获取商品的规格
 */
function goods_product($goods_id){
	$db = M('goods_spec');
	$list = $db->where("goods_id ='{$goods_id}'")->group("spec_id")->order("id asc")->field("spec_name,spec_id")->select();
	if(!empty($list)){
		foreach ($list as $i=>$va){
			$value[$i] = $db->where("goods_id='{$goods_id}' and spec_id='{$va['spec_id']}'")->field("spec_value")->select();
			foreach ($value[$i] as $k=>$vv){
				$valuelist[$i][] = $vv['spec_value'];
			}
			$list[$i]['value'] = $valuelist[$i];
		}
	}
	return $list;
}
/**
 * 根据规格查找详细的规格
 * @param unknown $goods_id 商品的id
 * @param string $spec 规格
 * @return string
 */
function spec_detail($goods_id,$spec=null){
	if(empty($spec)){
		return "无规格";
	}else{
		$spec = explode(",",$spec);
		$html = "";
		foreach ($spec as $i=>$va){
			 $spec_name[$i] = M('goods_spec')->where("spec_value='{$va}' and goods_id='{$goods_id}'")->order("id desc")->getField('spec_name');
		     $html .= "&nbsp;&nbsp;".$spec_name[$i].":".$va;	 
		}
		return $html;
	}
}
/**
 * 支付方式
 */
function order_pay_status($paytype){
	switch ($paytype){
		case '0':
			$payname = "货到付款";
			break;
		case '1':
			$payname = "微信支付";
			break;
		case '2':
			$payname = "支付宝支付";
		break;
		case '3':
			$payname = "银联支付";
		break;
		case '4':
			$payname = "财付通支付";
		break;
		default:
			$payname = "货到付款";
		break;
	}
	return $payname;
}
//订单状态
function order_status($status){
	switch ($status){
		case '0':
			$name = "未付款";
		break;
		case '1':
			$name = "待发货";
		break;
		case '2':
			$name = "部分发货";
		break;
		case '3':
			$name = "待收货";
		break;
		case '4':
			$name = "待评价";
		break;
		case '5':
			$name = "退款审核中";
		break;
		case '6':
			$name = "已成功退款";
		break;
		case '8':
			$name = "已评价";
		break;
	}
	return $name;
}
/**
 * 查找微信内容
 */
function wx_status_name($status,$status_id){
	switch ($status){
		//文本
		case '1':
			$name = M('wx_text')->where("id='{$status_id}'")->getField('text');
		break;
		case '2':
			//图文
			$status_id = explode(",",$status_id);
			$data['id'] = array('in',$status_id);
			$names = M('wx_imgtext')->where($data)->field('title')->select();
			if(!empty($names)){
				foreach ($names as $i=>$va){
					$namearray[] = $va['title'];
				}
				$name = join(",",$namearray);
			}else{
				$name = "";
			}
		break;
		case '3':
			//语音
			$name = M('wx_voice')->where("id='{$status_id}'")->getField('name');
		break;
		case '4':
			//视频
			$name = M('wx_video')->where("id='{$status_id}'")->getField('name');
			break;
		case '5':
			//图片
			$name = M('wx_image')->where("id='{$status_id}'")->getField('photo');
			break;
		default:
			return 0;
			break;
	}
	return $name;
}
/**
 * 获取用户信息
 */
function userinfo($uid){
	$user = M('user')->where("id='{$uid}'")->find();
	if(empty($user['head_img'])){
		$user['head_img'] = "/Public/home/img/10.jpg";
	}
	return $user;
}
/**
 * 获取区域名称
 */
function area_name($areaid){
	if(is_array($areaid)){
		$data['id'] = array('in',$areaid);
		$name = M('region')->where($data)->field('name')->select();
		$namearray = array();
		foreach ($name as $va){
			$namearray[]  = $va['name'];
		}
		return  $namearray;
	}else{
		$name = M('region')->where("id='{$areaid}'")->getField('name');
		return $name;
	}
	
}
/**
 *
 */
function url_encode($str) {
	if(is_array($str)) {
		foreach($str as $key=>$value) {
			$str[urlencode($key)] = url_encode($value);
		}
	} else {
		$str = urlencode($str);
	}

	return $str;
}
/**
 * 用户资金说明
 */
function fund_log_name($type){
	switch ($type){
		case '1':
			$name = "购买商品";
		break;
	}
	return $name;
}
//公私
function key_key(){
	$key = '-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDAbfx4VggVVpcfCjzQ+nEiJ2DLnRg3e2QdDf/m/qMvtqXi4xhw
vbpHfaX46CzQznU8l9NJtF28pTSZSKnE/791MJfVnucVcJcxRAEcpPprb8X3hfdx
KEEYjOPAuVseewmO5cM+x7zi9FWbZ89uOp5sxjMnlVjDaIczKTRx+7vn2wIDAQAB
AoGAZzUWajxKTZeJqh5FjBgmwZi5M7voFynZAjRWAkCkqZye0FfY7e70kA92C1AL
aVqySnNr4WYZuGorEeOFGqHIv1XSowTLgfLkVBZ/SXiep2QYJrR0YevjysvLnTfb
mrdWCqWSj+0AlQg+AvDA/qtvBVMxKymbpo+4bj5H2pPPZ1ECQQDi1PwJQJBYPbpL
vGmP3AmWg467tCeQ+aJGgtQTOK5BH+p0BWFVDX583R437vllkKI8EXgZfqQfsQcj
7XUAXyZVAkEA2SyFbO8roH9JLrEoxxKGeiGZvhPfNl9nXLhX0OFS0ywQaVBJno39
9W5bX5iP5Jzeb3UWsZ/TxzhGc/b4WjAlbwJBAOFuIn1feRT5Y+hY++BJIg4/+N57
EMd4ENpas0HXFvcKLQvZPP42Rvr5FksoaRuTPmjMQ7uyrJICccI3AAy6g3ECQQDE
AyH9+zRmLNxRj0advsOvUcpgu7DYc21oS12/Qs+tl3TMiNGZkNDphwxjkOA217sP
4B92fCn6AnncSslHJXNzAkBo6ujxqIfrZMOG3ON9nXxkWlq39GFS6CzXWscHA3Xz
FMVT1WWU3FR2Kf2QSKiMGv02YcI2xfowim3JnT6600N0
-----END RSA PRIVATE KEY-----';
	return $key;
}
//解密
function encript_basc64($es){
	$private_key = key_key();
	openssl_private_decrypt(base64_decode($es),$decrypted,$private_key);
	$encrypt_exist=false;
	if(!empty($decrypted)) {
		$arr = json_decode($decrypted, true);
		if(array_key_exists("encrypt",$arr)) {
			if($arr['encrypt']=="yes") $encrypt_exist=true;
		}
	}
	if(!$encrypt_exist){
		return "";
	}else{
		return $arr['password'];
		
	} 
}
function i_array_column($input, $columnKey,$indexKey=null){
	if(!function_exists('array_column')){
		$columnKeyIsNumber  = (is_numeric($columnKey))?true:false;
		$indexKeyIsNull            = (is_null($indexKey))?true :false;
		$indexKeyIsNumber     = (is_numeric($indexKey))?true:false;
		$result                         = array();
		foreach((array)$input as $key=>$row){
			if($columnKeyIsNumber){
				$tmp= array_slice($row, $columnKey, 1);
				$tmp= (is_array($tmp) && !empty($tmp))?current($tmp):null;
			}else{
				$tmp= isset($row[$columnKey])?$row[$columnKey]:null;
			}
			if(!$indexKeyIsNull){
				if($indexKeyIsNumber){
					$key = array_slice($row, $indexKey, 1);
					$key = (is_array($key) && !empty($key))?current($key):null;
					$key = is_null($key)?0:$key;
				}else{
					$key = isset($row[$indexKey])?$row[$indexKey]:0;
				}
			}
			$result[$key] = $tmp;
		}
		return $result;
	}else{
		return array_column($input, $columnKey, $indexKey);
	}
}
/**
 * php 实现js escape 函数
 * @param [type] $string [description]
 * @param string $encoding [description]
 * @return [type]   [description]
 */
function escape($string, $encoding = 'UTF-8'){
	$return = null;
	for ($x = 0; $x < mb_strlen($string, $encoding);$x ++)
	{
		$str = mb_substr($string, $x, 1, $encoding);
		if (strlen($str) > 1) { // 多字节字符
			$return .= "%u" . strtoupper(bin2hex(mb_convert_encoding($str, 'UCS-2', $encoding)));
		} else {
			$return .= "%" . strtoupper(bin2hex($str));
		}
	}
	return $return;
}
/**
 * php 实现 js unescape函数
 * @param [type] $str [description]
 * @return [type]  [description]
 */
function unescape($str) {
	$str = rawurldecode($str);
	preg_match_all("/(?:%u.{4})|.{4};|&#\d+;|.+/U",$str,$r);
	$ar = $r[0];
	foreach($ar as $k=>$v) {
		if(substr($v,0,2) == "%u"){
			$ar[$k] = iconv("UCS-2","utf-8//IGNORE",pack("H4",substr($v,-4)));
		} elseif(substr($v,0,3) == "") {
			$ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,3,-1)));
		} elseif(substr($v,0,2) == "&#") {
			echo substr($v,2,-1)."";
			$ar[$k] = iconv("UCS-2","utf-8",pack("n",substr($v,2,-1)));
		}
	}
	return join("",$ar);
}

/**
 * 特殊的字符
 * @param [type] $str [description]
 * @return [type]  [description]
 */
function makeSemiangle($str) {
	$arr = array(
			'０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
			'５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
			'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
			'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
			'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
			'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
			'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
			'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
			'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
			'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
			'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
			'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
			'ｙ' => 'y', 'ｚ' => 'z',
			'（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',
			'】' => ']', '〖' => '[', '〗' => ']', '｛' => '{', '｝' => '}', '《' => '<',
			'》' => '>',
			'％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',
			'：' => ':', '。' => '.', '、' => ',', '，' => '.', '、' => '.',
			'；' => ';', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',
			'”' => '"','“' => '"',"'"=> "`", '‘' => '`', '｜' => '|', '〃'=>'"',
			'　' => ' ','．' => '.');
	return strtr($str, $arr);
}
/**
 * 数字转人名币
 * @param [type] $num [description]
 * @return [type]  [description]
 */
function num2rmb ($num) {
	$c1 = "零壹贰叁肆伍陆柒捌玖";
	$c2 = "分角元拾佰仟万拾佰仟亿";
	$num = round($num, 2);
	$num = $num * 100;
	if (strlen($num) > 10) {
		return "oh,sorry,the number is too long!";
	}
	$i = 0;
	$c = "";
	while (1) {
		if ($i == 0) {
			$n = substr($num, strlen($num)-1, 1);
		} else {
			$n = $num % 10;
		}
		$p1 = substr($c1, 3 * $n, 3);
		$p2 = substr($c2, 3 * $i, 3);
		if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
			$c = $p1 . $p2 . $c;
		} else {
			$c = $p1 . $c;
		}
		$i = $i + 1;
		$num = $num / 10;
		$num = (int)$num;
		if ($num == 0) {
			break;
		}
	}
	$j = 0;
	$slen = strlen($c);
	while ($j < $slen) {
		$m = substr($c, $j, 6);
		if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
			$left = substr($c, 0, $j);
			$right = substr($c, $j + 3);
			$c = $left . $right;
			$j = $j-3;
			$slen = $slen-3;
		}
		$j = $j + 3;
	}
	if (substr($c, strlen($c)-3, 3) == '零') {
		$c = substr($c, 0, strlen($c)-3);
	} // if there is a '0' on the end , chop it out
	return $c . "整";
}
/**
 * 系统加密方法
 *
 * @param string $data
 *        	要加密的字符串
 * @param string $key
 *        	加密密钥
 * @param int $expire
 *        	过期时间 单位 秒
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function think_encrypt($data, $key = '', $expire = 0) {
	$key = md5 ( empty ( $key ) ? C ( 'DATA_AUTH_KEY' ) : $key );

	$data = base64_encode ( $data );
	$x = 0;
	$len = strlen ( $data );
	$l = strlen ( $key );
	$char = '';

	for($i = 0; $i < $len; $i ++) {
		if ($x == $l)
			$x = 0;
		$char .= substr ( $key, $x, 1 );
		$x ++;
	}

	$str = sprintf ( '%010d', $expire ? $expire + time () : 0 );

	for($i = 0; $i < $len; $i ++) {
		$str .= chr ( ord ( substr ( $data, $i, 1 ) ) + (ord ( substr ( $char, $i, 1 ) )) % 256 );
	}
	return str_replace ( array (
			'+',
			'/',
			'='
	), array (
			'-',
			'_',
			''
	), base64_encode ( $str ) );
}

/**
 * 系统解密方法
 *
 * @param string $data
 *        	要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param string $key
 *        	加密密钥
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function think_decrypt($data, $key = '') {
	$key = md5 ( empty ( $key ) ? C ( 'DATA_AUTH_KEY' ) : $key );
	$data = str_replace ( array (
			'-',
			'_'
	), array (
			'+',
			'/'
	), $data );
	$mod4 = strlen ( $data ) % 4;
	if ($mod4) {
		$data .= substr ( '====', $mod4 );
	}
	$data = base64_decode ( $data );
	$expire = substr ( $data, 0, 10 );
	$data = substr ( $data, 10 );

	if ($expire > 0 && $expire < time ()) {
		return '';
	}
	$x = 0;
	$len = strlen ( $data );
	$l = strlen ( $key );
	$char = $str = '';

	for($i = 0; $i < $len; $i ++) {
		if ($x == $l)
			$x = 0;
		$char .= substr ( $key, $x, 1 );
		$x ++;
	}

	for($i = 0; $i < $len; $i ++) {
		if (ord ( substr ( $data, $i, 1 ) ) < ord ( substr ( $char, $i, 1 ) )) {
			$str .= chr ( (ord ( substr ( $data, $i, 1 ) ) + 256) - ord ( substr ( $char, $i, 1 ) ) );
		} else {
			$str .= chr ( ord ( substr ( $data, $i, 1 ) ) - ord ( substr ( $char, $i, 1 ) ) );
		}
	}
	return base64_decode ( $str );
}

	